package com.ly.controller;

import com.github.pagehelper.PageInfo;
import com.ly.bean.EasybuyProduct;
import com.ly.bean.EasybuySeckillGoods;
import com.ly.bean.EasybuySeller;
import com.ly.config.FastDFSClient;
import com.ly.service.ProductService;
import com.ly.service.SeckillGoodsService;
import com.ly.util.NewFileNameUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Date;
import java.util.*;


/**
 * @author 李岩
 * @date 2021/12/14-15:04
 * @describe
 */
@Controller
@RequestMapping("/product/")
public class ProductController {
    private final Logger logger= LoggerFactory.getLogger(ProductController.class);
    private ProductController(){
        System.out.println("ProductController   的controller层");
    }
    @Reference(url = "dubbo://localhost:20851")
    private ProductService productService;
    @Reference(url = "dubbo://localhost:20887")
    private SeckillGoodsService seckillGoodsService;

    @PostMapping("addProduct")
    public String addProduct(EasybuyProduct product, @RequestParam("proimg") MultipartFile proimg  , @RequestParam("imgs") List<String> imgs, HttpSession session){
        try {
            logger.info("卖家添加商品");
            logger.info("商品的描述:" + product.getDescription());
            String url = "";

            EasybuySeller seller = (EasybuySeller) session.getAttribute("seller");
            if (seller == null)
                return "redirect:/login.html";
            //处理文件上传的功能
            //1.取文件的扩展名
            String fileName = proimg.getOriginalFilename();
            //System.out.println("fileName="+fileName);

            product.setSellerId( seller.getSellerId() );
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
            //System.out.println("extName="+extName);
            if(fileName!=null &&!"".equals(fileName)){
                //获取文件的扩展类型
                //fileName = NewFileNameUtil.getNewFileName(fileName);

                //String path = "D:\\Idea\\workspace\\dubbo_springboot\\easybuy_springboot_dubbo\\easybuy_seller_web\\src\\main\\resources\\static\\images\\"+fileName;
                //proimg.transferTo(new File(path));

                // 2、创建一个 FastDFS 的客户端
                FastDFSClient fastDFSClient = new FastDFSClient("classpath:fdfs_client.conf");
                // 3、执行上传处理
                String path = fastDFSClient.uploadFile(proimg.getBytes(), extName);
                // 4、拼接返回的 url 和 ip 地址，拼装成完整的 url
                url = "http://192.168.25.133/" + path;
                System.out.println("url=   "+url);

            }
            product.setIsdelete(2);
            product.setFilename(url);
            productService.addProduct(product,imgs);
            return "redirect:/index.html";

        } catch (Exception e) {
            logger.error("添加商品有误   "+e);
        }
        return "redirect:/error.html" ;
    }

    @PostMapping("kindLoad")
    @ResponseBody
    public Map<String,Object> uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HashMap<String, Object> hashMap = new HashMap<>();
        try {
            logger.info("进入富文本编辑器的图片上传");
            // 文件保存目录路径
            /*String savePath = "D:\\Idea\\workspace\\dubbo_springboot\\easybuy_springboot_dubbo\\easybuy_seller_web\\src\\main\\resources\\static\\images\\";
            String saveUrl  = request.getContextPath() + "/images/";*/

            // 定义允许上传的文件扩展名
            /*HashMap<String, String> extMap = new HashMap<String, String>();
            extMap.put("image", "gif,jpg,jpeg,png,bmp");*/


            // 最大文件大小
            long maxSize = 1000000;
            response.setContentType("text/html; charset=UTF-8");

           /* File uploadDir = new File(savePath);
            // 判断文件夹是否存在,如果不存在则创建文件夹
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            String dirName = request.getParameter("dir");
            if (dirName == null) {
                dirName = "image";
            }*/

            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = mRequest.getFileMap();
            String fileName = null;
            for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, MultipartFile> entry = it.next();
                MultipartFile mFile = entry.getValue();
                fileName = mFile.getOriginalFilename();
                // 检查文件大小
                if (mFile.getSize() > maxSize) {
                    hashMap.put("error",1);
                    hashMap.put("message","上传文件大小超过限制");
                    return hashMap;
                }

                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
                // 把图片保存到图片服务器上
                FastDFSClient imageClient = new FastDFSClient("classpath:fdfs_client.conf");
                // 上传图片完毕后返回图片在服务器的位置
                String savepath = imageClient.uploadFile(mFile.getBytes(), fileExt);
                String bookImagePath = "http://192.168.25.133/" + savepath;
                System.out.println("bookImagePath:" + bookImagePath);
                // 把文件从服务器复制到本地
                // 为了防止测试的时候多次部署，导致之前的上传图片丢失,额外做得补救措施


                /*if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    hashMap.put("error",1);
                    hashMap.put("message","上传文件扩展名是不允许的扩展名");
                    return hashMap;
                }
                UUID uuid = UUID.randomUUID();

                savePath = savePath  + uuid.toString() +"."+ fileExt;
                saveUrl +=uuid.toString() +"."+ fileExt;
                BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(savePath));
                FileCopyUtils.copy(mFile.getInputStream(), outputStream);

                String serverPath="D:\\Idea\\workspace\\dubbo_springboot\\easybuy_springboot_dubbo\\easybuy_seller_web\\target\\classes\\static\\images\\";
                serverPath = serverPath  + uuid.toString() +"."+ fileExt;
                FileCopyUtils.copy(new File(savePath),new File(serverPath));*/

                hashMap.put("error",0);
                hashMap.put("url",bookImagePath);
                logger.info("进入富文本编辑器的图片上传  完成");
                return hashMap;
            }

        } catch (Exception ex) {
            logger.error("进入富文本编辑器的图片上传  出现异常  "+ex);
        }
        hashMap.put("error",1);
        hashMap.put("message","进入富文本编辑器的图片上传  失败");
        return hashMap;
    }

    @PostMapping("layuiload")
    @ResponseBody
    public Map<String, Object> layuiload(MultipartFile file, HttpServletRequest request){
        System.out.println("商品的描述  "+file.getOriginalFilename());
        Map<String, Object> map = new HashMap<String, Object>();
        //String path ="D:\\Idea\\workspace\\dubbo_springboot\\easybuy_springboot_dubbo\\easybuy_seller_web\\src\\main\\resources\\static\\images\\";
        try {
            //file.transferTo(new File(path + file.getOriginalFilename()));
            String fileName = file.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 把图片保存到图片服务器上
            FastDFSClient imageClient = new FastDFSClient("classpath:fdfs_client.conf");
            // 上传图片完毕后返回图片在服务器的位置
            String savepath = imageClient.uploadFile(file.getBytes(), fileExt);
            String bookImagePath = "http://192.168.25.133/" + savepath;
            System.out.println("bookImagePath:" + bookImagePath);
            // 把文件从服务器复制到本地
            // 为了防止测试的时候多次部署，导致之前的上传图片丢失,额外做得补救措施

            map.put("imgurl", bookImagePath);
            map.put("msg", "上传成功！");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return map;
    }

    //根据登录卖家的信息，获取卖家中售卖的商品列表
    @RequestMapping("selectProductBySellerId")
    public String selectProductBySellerId(String pageNum, @CookieValue("sellerId") String sellerId, Model model){
        try {
            logger.info("分页展示该商家的商品,pageNum= "+pageNum+"; sellerId= "+sellerId);
            PageInfo<EasybuyProduct> pageInfo = productService.selectProductBySellerId(pageNum, sellerId);
            System.out.println(pageInfo.getList());
            model.addAttribute("pageInfo",pageInfo);
            return "product_list";
        } catch (Exception e) {
            logger.error("分页展示该商家的商品 出现异常 "+e);
        }
        return "error";
    }
    //商家向平台申请 把商品加到秒杀表中   @RequestParam("productId") List<Integer> productIds
    @RequestMapping("applyKillProduct")
    public String applyKillProduct(Integer productId,Model model){
        logger.info("商家向平台申请 把商品加到秒杀表中 "+productId);
        try {
            EasybuyProduct product = productService.selectProductByPrimaryKey(productId);
            model.addAttribute("product",product);
            return "product_kill_apply";
        } catch (Exception e) {
            logger.error("商家向平台申请 把商品加到秒杀表中 出现异常"+e);
        }
        return "error";
    }
    //将要添加到秒杀列表的相应信息添加到 秒杀表里面
    @RequestMapping("confirmApplyKillProduct")
    public String confirmApplyKillProduct(EasybuySeckillGoods seckillGoods,Model model){
        try {

            logger.info("将要添加到秒杀列表的相应信息添加到 秒杀表里面"+seckillGoods);
            seckillGoods.setStockCount(seckillGoods.getNum());
            seckillGoods.setCreateTime(new Date(new java.util.Date().getTime()));
            seckillGoods.setStatus("0");
            seckillGoodsService.insertSelective(seckillGoods);
            return "redirect:/product/selectProductBySellerId";
        } catch (Exception e) {
            logger.error("将要添加到秒杀列表的相应信息添加到 秒杀表里面 出现异常"+e);
        }
        return "error";
    }
}
